package nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


public class BufferTest {

    public static void main(String[] args) throws IOException {
        String file = "/Users/sevenluo/dev_tools/IdeaProjects/netty-learn/netty-practice/test.txt";
        RandomAccessFile accessFile = new RandomAccessFile(file,"rw");
        FileChannel fileChannel = accessFile.getChannel();
        // 20个字节
        ByteBuffer buffer = ByteBuffer.allocate(20);
        int bytesRead = fileChannel.read(buffer);
        // buffer.put()也能写入buffer
        while(bytesRead!=-1){
            // 写切换到读
            buffer.flip();

            while(buffer.hasRemaining()){
                System.out.println((char)buffer.get());
            }
            // buffer.rewind() 重新读
            // buffer.mark() 标记position
            // buffer.reset() 恢复
            // 清除缓冲区
            buffer.clear();
            // 清除读过的数据
            // buffer.compact();
            System.out.println("=================");
            bytesRead = fileChannel.read(buffer);
        }
    }
}